package com.my.easypoi.handler.verify;

import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import com.my.easypoi.domain.UserValidation;

import java.util.*;

/*利用ThreadLocal验证一次excel的数据--需要及时释放  还有db的数据*/
public class ImportVerifyHandler  implements IExcelVerifyHandler<UserValidation> {

    private final ThreadLocal<List<UserValidation>> threadLocal = new ThreadLocal<>();

    @Override
    public ExcelVerifyHandlerResult verifyHandler(UserValidation obj) {
        StringJoiner joiner = new StringJoiner(",");
        // 根据姓名与身份证判断数据是否重复
        String name = obj.getName();
        int age = obj.getAge();
        // mock 数据库
        boolean duplicates = checkForDuplicates(name, age);
        if (duplicates) {
            joiner.add("数据与数据库数据重复");
        }

        List<UserValidation> threadLocalVal = threadLocal.get();
        if (threadLocalVal == null) {
            threadLocalVal = new ArrayList<>();
        }
        threadLocalVal.forEach(e -> {
            if (e.equals(obj)) {
                int lineNumber = e.getRowNum() + 1;
                joiner.add("数据与第" + lineNumber + "行重复");
            }
        });
        // 添加本行数据对象到ThreadLocal中
        threadLocalVal.add(obj);
        threadLocal.set(threadLocalVal);

        if (joiner.length() != 0) {
            return new ExcelVerifyHandlerResult(false, joiner.toString());
        }
        return new ExcelVerifyHandlerResult(true);
    }


    /**
     * 校验是否重复
     */
    public boolean checkForDuplicates(String name, int age) {
        List<UserValidation> dbList = new ArrayList();
        dbList.add(new UserValidation("1","测试",25,new Date(),
                1, Arrays.asList("喝酒","抽烟","打架")));
        // 姓名与年龄相等个数不等于0则为重复
        return dbList.stream().anyMatch(
                e -> e.getName().equals(name)
                        && e.getAge()==age
        );
    }
    public ThreadLocal<List<UserValidation>> getThreadLocal() {
        return threadLocal;
    }
}
